package com.madzone.gae.filem;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.madzone.wiki.gae.ds.model.PMF;

public class FileInputStream extends InputStream {
	
	private int position = 0;
	byte[] fileContent = null;
	
	public FileInputStream(File file) {
		this(file.getAbsolutePath());
	}

	public FileInputStream(String absolutePath) {
		PersistenceManager pm = PMF.getPM();
		String query = "select from " + com.madzone.gae.filem.model.BinaryFile.class.getName() + " where fileName == '" + absolutePath + "'";
		List<com.madzone.gae.filem.model.File> result = (List<com.madzone.gae.filem.model.File>) pm.newQuery(query).execute();
		if (result.size() > 0) {
			com.madzone.gae.filem.model.File file = result.get(0);
			fileContent = file.getContentBytes();
		}
		//pm.close();
	}

	@Override
	public int read() throws IOException {
		if (fileContent == null || position >= fileContent.length) {
			return -1;
		} else {
			return fileContent[position++];
		}
	}

}
